package com.gongpingjialoan.view;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.CarBuyDetailActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/18.
 */
public class MainRecomendView extends FrameLayout {

    private MyListView mListView;

    private RadioGroup mRadioGroup;

    private CarSourceListAdapter carSourceAdapter;

    private List<CarSource> recomendCarSources, browseCarSources;

    private NetDataJson mRecomendNetDataJson, browseNetDataJson;

    private boolean isLoadRecomendCar = false;
    private boolean isLoadBrowseCar = false;

    public MainRecomendView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(getContext()).inflate(R.layout.main_list_fragment, this, true);
        mListView = (MyListView) findViewById(R.id.list);
        mRadioGroup = (RadioGroup) findViewById(R.id.title_tab);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio1) {
                    StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_recommend", System.currentTimeMillis(), 1f));
                    carSourceAdapter.setData(recomendCarSources);
                } else if (checkedId == R.id.radio2) {
                    StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_viewRecords", System.currentTimeMillis(), 1f));
                    carSourceAdapter.setData(browseCarSources);
                }
            }
        });
        recomendCarSources = new ArrayList<>();
        browseCarSources = new ArrayList<>();
        carSourceAdapter = new CarSourceListAdapter(context);
        mListView.setAdapter(carSourceAdapter);
        getRecomendCars();
        getBrowseCars();

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(getContext(), CarBuyDetailActivity.class);
                CarSource carSource = (CarSource) view.getTag(R.id.tag_second);
                if (carSource == null) return;
                intent.putExtra("typevalue", String.valueOf(carSource.mId));
                getContext().startActivity(intent);
            }
        });
    }


    public void getRecomendCars() {
        if (mRecomendNetDataJson == null) {
            mRecomendNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {

                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = json.getJSONArray("cars");
                        recomendCarSources = getDataFromJsonArray(jsonArray, false);
                        isLoadRecomendCar = true;
                        if (mRadioGroup.getCheckedRadioButtonId() == R.id.radio1) {
                            carSourceAdapter.setData(recomendCarSources);
                        }
                        setVisRecomend();
                    } catch (JSONException e) {
                    }
                }
            });
        }
        mRecomendNetDataJson.setUrl(API.get_recomend_cars);
        mRecomendNetDataJson.addParam("city", MainActivity.main.currentCity);
        mRecomendNetDataJson.request("get");
    }

    public void getBrowseCars() {
        if (browseNetDataJson == null) {
            browseNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {

                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = json.getJSONArray("records");
                        browseCarSources = getDataFromJsonArray(jsonArray, true);
                        isLoadBrowseCar = true;
                        if (mRadioGroup.getCheckedRadioButtonId() == R.id.radio2) {
                            carSourceAdapter.setData(browseCarSources);
                        }
                        setVisRecomend();
                    } catch (JSONException e) {
                    }
                }
            });
        }
        browseNetDataJson.setUrl(API.collectHistory);
        browseNetDataJson.addParam("record_type", "buy_car");
        browseNetDataJson.request("get");

    }


    private void setVisRecomend() {
        if (isLoadRecomendCar && isLoadBrowseCar) {
            if (MainActivity.main.assessmentFragment.isAdded()) {
                MainActivity.main.assessmentFragment.setRecomendVis();
            }
        }
    }


    private List<CarSource> getDataFromJsonArray(JSONArray jsonArray, boolean isBrowse) throws JSONException {
        // Log.e("getDataFromJsonArray", "getDataFromJsonArray");
        List<CarSource> carSourceDataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);

            carSrc.mCity = object.getString("city");
            carSrc.distance = object.getString("distance");
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = object.getString("time");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            // carSrc.mRecommend = object.getString("recommend");
            carSrc.isactive = object.getBoolean("seller_active");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.dealer_category = object.getString("dealer_category");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");
            carSrc.hasmodel = object.getString("has_model_detail");
            carSrc.origin_price = object.getString("origin_price");
            carSrc.lowest_price = object.getString("lowest_price");
            carSrc.last_price = object.getString("last_price");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.setBrand(object.getString("brand_slug"));
            carSrc.setModel(object.getString("model_slug"));
            if (isBrowse) {
                carSrc.review = object.getString("review");
                carSrc.review_type = object.getString("review_type");
            }
            carSrc.mUrl = carSrc.mThumbnail;
            carSrc.cs_clean = object.getBoolean("cs_clean");
            carSourceDataList.add(carSrc);
        }
        return carSourceDataList;
    }


    public void canalTask() {
        if (mRecomendNetDataJson != null) {
            mRecomendNetDataJson.cancelTask();
            mRecomendNetDataJson = null;
        }
        if (browseNetDataJson != null) {
            browseNetDataJson.cancelTask();
            browseNetDataJson = null;
        }
    }

}
